/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.netbeans.modules.j2ee.earproject.ui.wizards;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.netbeans.api.java.classpath.ClassPath;
import org.netbeans.api.java.platform.JavaPlatformManager;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectManager;
import org.netbeans.api.j2ee.core.Profile;
import org.netbeans.modules.j2ee.earproject.EarProject;
import org.netbeans.modules.j2ee.earproject.EarProjectTest;
import org.netbeans.modules.j2ee.earproject.TestPlatformProvider;
import org.netbeans.modules.j2ee.earproject.test.EarTestCase;
import org.netbeans.modules.j2ee.earproject.test.TestUtil;
import org.netbeans.modules.j2ee.earproject.ui.customizer.EarProjectProperties;
import org.netbeans.spi.java.classpath.support.ClassPathSupport;
import org.netbeans.spi.project.SubprojectProvider;
import org.netbeans.spi.project.support.ant.EditableProperties;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;

/**
 * @author Martin Krauskopf
 */
public class NewEarProjectWizardIteratorTest extends EarTestCase {
    
    private static final String DEFAULT_PLATFORM_ROOT = "1.5";

    private String oldNbUser;

    /**
     * Generates a project in the same (or very similar) manner as would be
     * generated by the user using <em>New Enterprise Application</em> wizard.
     * May be used for generating project instances in tests.
     */
    public static void generateEARProject(
            File prjDirF, String name, Profile j2eeProfile,
            String serverInstanceID, String warName,
            String jarName, String carName, String mainClass,
            String platformName, String sourceLevel) throws IOException {
        NewEarProjectWizardIterator.testableInstantiate(prjDirF, name,
                j2eeProfile, serverInstanceID, warName, jarName,
                carName, mainClass, platformName, sourceLevel, null, null, false);
    }
    
    /**
     * Generates an empty Enterprise Application project, i.e. without
     * submodules.
     *
     * @see #generateEARProject(File, String, String, String, String, String, String, String, String, String)
     */
    public static void generateEARProject(File earDirF, String name,
            Profile j2eeProfile, String serverID) throws IOException {
        generateEARProject(earDirF, name, j2eeProfile, serverID, null, null, null,
                null, null, null);
    }
    
    public NewEarProjectWizardIteratorTest(String testName) {
        super(testName);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        
        clearWorkDir();
        
        
        FileObject scratch = FileUtil.toFileObject(getWorkDir());
        FileObject defaultPlatformBootRoot = scratch.createFolder(DEFAULT_PLATFORM_ROOT);
        ClassPath defBCP = ClassPathSupport.createClassPath(new URL[] { defaultPlatformBootRoot.getURL() });

        TestUtil.initLookup(this, new TestPlatformProvider(defBCP, defBCP));
        
        assertEquals("No Java platforms found.", 2, JavaPlatformManager.getDefault().getInstalledPlatforms().length);
    }

    public void testTestableInstantiate() throws Exception {
        File dirF = new File(getWorkDir(), "testEA");
        String name = "Test EnterpriseApplication";
        Profile j2eeProfile = Profile.J2EE_14;
        String warName = null;
        String jarName = null;
        String carName = null;
        String mainClass = null;
        String platformName = null;
        String sourceLevel = null;
        
        Set result = NewEarProjectWizardIterator.testableInstantiate(dirF, name,
                j2eeProfile, TestUtil.SERVER_URL, warName, jarName,
                carName, mainClass, platformName, sourceLevel, null, null, false);
        
        Set<FileObject> expResult = new HashSet<FileObject>();
        FileObject testEAFO = FileUtil.toFileObject(new File(getWorkDir(), "testEA"));
        assertNotNull("testEA directory", testEAFO);
        expResult = Collections.singleton(testEAFO);
        assertEquals(expResult, result);
        
        EditableProperties ep = TestUtil.loadProjectProperties(testEAFO);
        assertNull("app.client is not set", ep.getProperty(EarProjectProperties.APPLICATION_CLIENT));
        assertEquals("client.module.uri is empty", "", ep.getProperty(EarProjectProperties.CLIENT_MODULE_URI));
    }
    
    public void testTestableInstantiateWithAppClient() throws Exception {
        String resource = "org-netbeans-modules-j2ee-clientproject/application-client-5.xml";
        assertNotNull("application client registered", FileUtil.getConfigFile(resource));
        File dirF = new File(getWorkDir(), "testEA");
        String name = "Test EnterpriseApplication";
        Profile j2eeProfile = Profile.J2EE_14;
        String warName = null;
        String jarName = null;
        String carName = "testEA-app-client";
        String mainClass = "testEA.app.client.Main";
        String platformName = null;
        String sourceLevel = null;
        
        Set result = NewEarProjectWizardIterator.testableInstantiate(dirF, name,
                j2eeProfile, TestUtil.SERVER_URL, warName, jarName,
                carName, mainClass, platformName, sourceLevel, null, null, false);
        
        Set<FileObject> expResult = new HashSet<FileObject>();
        File testEA = new File(getWorkDir(), "testEA");
        FileObject testEAFO = FileUtil.toFileObject(testEA);
        assertNotNull("testEA directory", testEAFO);
        FileObject testEAClientFO = FileUtil.toFileObject(new File(testEA, "testEA-app-client"));
        assertNotNull("testEA-app-client directory", testEAClientFO);
        expResult.add(testEAFO);
        expResult.add(testEAClientFO);
        assertEquals(expResult, result);
        
        EditableProperties ep = TestUtil.loadProjectProperties(testEAFO);
        assertEquals("app.client set", "testEA-app-client", ep.getProperty(EarProjectProperties.APPLICATION_CLIENT));
        assertEquals("client.module.uri is set to app. client", "Test EnterpriseApplication/${app.client}", ep.getProperty(EarProjectProperties.CLIENT_MODULE_URI));
    }
    
    public void testTestableInstantiateWithWebAndEJBAppClient() throws Exception {
        String resource = "org-netbeans-modules-j2ee-clientproject/application-client-5.xml";
        assertNotNull("application client registered", FileUtil.getConfigFile(resource));
        File dirF = new File(getWorkDir(), "testEA");
        String name = "Test EnterpriseApplication";
        Profile j2eeProfile = Profile.J2EE_14;
        String warName = "testEA-war";
        String jarName = "testEA-ejb";
        String carName = "testEA-app-client";
        String mainClass = "testEA.app.client.Main";
        String platformName = null;
        String sourceLevel = null;
        
        Set result = NewEarProjectWizardIterator.testableInstantiate(dirF, name,
                j2eeProfile, TestUtil.SERVER_URL, warName, jarName,
                carName, mainClass, platformName, sourceLevel, null, null, false);
        
        Set<FileObject> expResult = new HashSet<FileObject>();
        File testEA = new File(getWorkDir(), "testEA");
        FileObject testEAFO = FileUtil.toFileObject(testEA);
        assertNotNull("testEA directory", testEAFO);
        FileObject testEAEjbFO = FileUtil.toFileObject(new File(testEA, "testEA-ejb"));
        assertNotNull("testEA-ejb directory", testEAEjbFO);
        FileObject testEAClientFO = FileUtil.toFileObject(new File(testEA, "testEA-app-client"));
        assertNotNull("testEA-app-client directory", testEAClientFO);
        FileObject testEAWebFO = FileUtil.toFileObject(new File(testEA, "testEA-war"));
        assertNotNull("testEA-war directory", testEAWebFO);
        
        expResult.add(testEAFO);
        expResult.add(testEAEjbFO);
        expResult.add(testEAClientFO);
        expResult.add(testEAWebFO);
        assertEquals(expResult, result);
        
        EditableProperties ep = TestUtil.loadProjectProperties(testEAFO);
        assertNull("app.client not set", ep.getProperty(EarProjectProperties.APPLICATION_CLIENT));
        assertEquals("client.module.uri is set to war", "testEA-war", ep.getProperty(EarProjectProperties.CLIENT_MODULE_URI));
        EarProjectTest.openProject((EarProject) ProjectManager.getDefault().findProject(testEAFO));
        
        doTestThatEJBWasAddedToWebAndAC(testEAWebFO, testEAClientFO); // #74123
    }
    
    static void doTestThatEJBWasAddedToWebAndAC( // #66546 and #74123
            final FileObject testEAWebFO, final FileObject testEAClientFO) throws IOException {
        
        Project testEAClientProject = ProjectManager.getDefault().findProject(testEAClientFO);
        SubprojectProvider acSubProjects = testEAClientProject.getLookup().lookup(SubprojectProvider.class);
        assertNotNull("application client has SubprojectProvider in its lookup", acSubProjects);
        assertEquals("ejb added to application client's", 1, acSubProjects.getSubprojects().size());
        
        Project testEAWebProject = ProjectManager.getDefault().findProject(testEAWebFO);
        SubprojectProvider webSubProjects = testEAWebProject.getLookup().lookup(SubprojectProvider.class);
        assertNotNull("web project has SubprojectProvider in its lookup", webSubProjects);
        assertEquals("ejb added to web project's", 1, webSubProjects.getSubprojects().size());
    }
    
}
